package com.lky.marshallmall.marshall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.lky.common.constant.AuthServerConstant;
import com.lky.common.exception.BizCodeEnum;
import com.lky.common.utils.R;
import com.lky.common.vo.MemberVo;
import com.lky.marshallmall.marshall.auth.feign.MemberFeignService;
import com.lky.marshallmall.marshall.auth.feign.ThirdPartFeignService;
import com.lky.marshallmall.marshall.auth.vo.UserLoginVo;
import com.lky.marshallmall.marshall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created by
 * autor : Marshall lky
 * datetime: 2021/4/23 8:55
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 发送一个请求直接跳转一个页面
     * SpringMVC viewcontroller 将请求和页面映射
     *
     * @return
     */


    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        //防止同一个手机号60秒内再次发送验证码
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (redisCode != null) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //60秒内不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //1.接口防刷。 TODO

        //2.验证码再次校验。存key-phone value-code
        String yzmCode = UUID.randomUUID().toString().substring(0, 5);
        String code = yzmCode + "_" + System.currentTimeMillis();
        //redis缓存验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code, AuthServerConstant.SMS_CODE_EXPIRE, TimeUnit.MINUTES);

        thirdPartFeignService.sendCode(phone, yzmCode, "3");
        return R.ok();
    }


    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
//            Map<String,String> errors = new HashMap<>();
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.marshallmall.com/reg.html";
        }
        //todo 调用远程服务进行注册 ,校验验证码
        String code = vo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            //验证码 校验成功
            if (code.equals(redisCode.split("_")[0])) {
                //删除验证码;令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //通过，注册调用远程会员服务
                R regist = memberFeignService.regist(vo);
                if (regist.getCode() == 0) {
                    return "redirect:http://auth.marshallmall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", (String) regist.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.marshallmall.com/reg.html";
                }

            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                //校验出错，转发到注册页
                return "redirect:http://auth.marshallmall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.marshallmall.com/reg.html";
        }
    }


    @PostMapping("/login")
    public String login(UserLoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession session) {
        //远程登陆
        R<MemberVo> login = memberFeignService.login(loginVo);
        if (login.getCode() == 0) {
            MemberVo data = login.getData(new TypeReference<MemberVo>() {
            });
            session.setAttribute(AuthServerConstant.SESSION_NAME, data);
            return "redirect:http://marshallmall.com";
        } else {
            HashMap<String, String> map = new HashMap<>();
            map.put("msg", (String) login.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.marshallmall.com/login.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.SESSION_NAME);
        if (attribute == null) {
            return "login.html";
        } else {
            return "redirect:http://marshallmall.com";
        }
    }

}
